package com.project.forlearning.service.impl;

import com.alibaba.fastjson.JSON;
import com.project.forlearning.constant.ResponseTool;
import com.project.forlearning.dao.BackAdminMapper;
import com.project.forlearning.pojo.Admin;
import com.project.forlearning.pojo.vo.ResponseInfo;
import com.project.forlearning.service.BackLoginService;
import com.project.forlearning.utils.StringUtils;
import com.project.forlearning.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class BackLoginServiceImpl implements BackLoginService {

    @Autowired
    private BackAdminMapper backAdminMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 管理员注册
     */
    @Override
    public synchronized String registerAdmin(String mail, String pass) throws MessagingException {
        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(mail, pass))
            return JSON.toJSONString(new ResponseInfo<>(504, "邮箱或密码不能为空或空串", false));

        //是否存在邮箱号
        if(backAdminMapper.queryAdmin(null, null, mail) != null)
            return JSON.toJSONString(new ResponseInfo<>(505, "存在重复邮箱号", false));

        //生成账号
        String adminName = StringUtils.createName();

        //加密
        String adminPass = StringUtils.tranPass(pass, adminName);

        //发送邮箱
        this.sendMail(adminName, mail);

        //注册
        Admin admin = new Admin();
        admin.setAdminPass(adminPass);
        admin.setAdminMail(mail);
        admin.setAdminName(adminName);

        if(backAdminMapper.registerAdmin(admin)){
            return JSON.toJSONString(new ResponseInfo<>(200,"注册成功",admin));
        }

        return JSON.toJSONString(new ResponseInfo<>(505, "注册失败，数据库添加信息错误", false));
    }

    /**
     * 管理员登录
     */
    @Override
    public String loginAdmin(String adminName, String pass, HttpServletRequest request) {
        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(adminName, pass))
            return JSON.toJSONString(new ResponseInfo<>(505, "账号或密码不能为空或空串", false));

        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(adminName, StringUtils.tranPass(pass, adminName)));
        Admin admin = (Admin) subject.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("admin", admin);
        map.put("token", TokenUtil.getToken(String.valueOf(admin.getAdminId()), admin.getAdminName(), request.getRemoteAddr()));
        return JSON.toJSONString(new ResponseInfo<>(200, "登录成功", map));
    }

    /**
     * 管理员修改密码
     * @param mail
     * @param pass
     * @return
     */
    @Override
    public String updateAdminPass(String mail, String pass) {

        //邮箱或密码不能为空或空串
        if(StringUtils.isEmpty(mail, pass))
            return JSON.toJSONString(new ResponseInfo<>(505, "邮箱或密码不能为空或空串", false));

        //判断邮箱号是否存在
        Admin admin = backAdminMapper.queryAdmin(null, null, mail);
        if(admin == null)
            return JSON.toJSONString(new ResponseInfo<>(404, "不存在邮箱号", false));

        //加密
        String newPass = StringUtils.tranPass(pass, admin.getAdminName());

        //封装新对象
        Admin newAdmin = new Admin();
        newAdmin.setAdminMail(mail);
        newAdmin.setAdminPass(newPass);

        //更改密码
        admin.setAdminPass(newPass);

        //更改数据库中的密码
        if(backAdminMapper.updateAdmin(newAdmin))
            return JSON.toJSONString(new ResponseInfo<>(ResponseTool.UPDATE_SUCCESS.code, ResponseTool.UPDATE_SUCCESS.msg, admin));

        return JSON.toJSONString(new ResponseInfo<>(ResponseTool.UPDATE_FAIL.code, ResponseTool.UPDATE_FAIL.msg, false));
    }

    /**
     * 注销
     */
    @Override
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return JSON.toJSONString(new ResponseInfo<>(200, "成功注销!", true));
    }

    /**
     * 发送邮箱
     */
    private void sendMail(String adminName, String mail) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, false);
        helper.setSubject("For learning | 管理员账号信息通知");
        String text = "<p>你好，您的账号为：</p><p>" + adminName +"</p><p>请记住您的管理员账号</p>";
        helper.setText(text, true);
        helper.setFrom("1804859224@qq.com");
        helper.setTo(mail);
        javaMailSender.send(message);
    }

}
